package info.liujiachen.security.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SpringBootApplication
@RestController
public class ApiLoginApp {

    @RequestMapping({"/", "/home"})
    public String home() {
        return "Everyone can read the home page." +
                "<br> <a href=\"user\">user</a>" +
                "<br> <a href=\"admin\">admin</a>" +
                "<br> <a href=\"logout\">logout</a>";
    }

    @RequestMapping("/user")
    public String user() {
        return "User and admin can read the user page." +
                "<br> <a href=\"admin\">admin</a>" +
                "<br> <a href=\"logout\">logout</a>";
    }

    @RequestMapping("/admin")
    public String admin() {
        return "User admin can read the admin page." +
                "<br> <a href=\"user\">user</a>" +
                "<br> <a href=\"logout\">logout</a>";
    }

    @RequestMapping("/api/login")
    public String login() {
        return "api";
    }

    @RequestMapping("/api/login/error")
    public String loginError() {
        return "error";
    }

    @RequestMapping("/api/login/success")
    public String loginSuccess(HttpServletRequest request, HttpServletResponse response) {
        return "success";
    }


    @RequestMapping("/error")
    public String error(HttpServletRequest request) {
        int code = (int) request.getAttribute("javax.servlet.error.status_code");
        switch (code) {
            case 404:
                return "Not Found." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
            case 403:
                return "No permission." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
            case 500:
                return "System exception." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
            default:
                return "Incomprehensible." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(ApiLoginApp.class, args);
    }

}
